import Router from 'koa-router'
import subscribe from 'redis-subscribe-sse'
import fs from 'fs'

const router = new Router()

router.get('/', async (ctx, next) => {
  ctx.type = 'text/html; charset=utf-8'
  ctx.body = fs.createReadStream('./index.html')
})

router.get('/stream', async function (ctx, next) {
  ctx.req.setTimeout(Number.MAX_VALUE)
  ctx.type = 'text/event-stream; charset=utf-8'

  ctx.set('Cache-Control', 'no-cache')
  ctx.set('Connection', 'keep-alive')

  const client = ctx.body = subscribe({
    channels: ['stock', 'user'],
    retry: 10000,
    host: '127.0.0.1',
    port: 6379,
    channelsAsEvents: false
  })

  ctx.req.on("close", function() {
    client.close()
  })
  ctx.req.on("error", function() {
    client.close()
  })
})

module.exports = router
